package com.atguigu.spzx.manager.config;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.utils.AuthContextUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: LoginAuthInterceptor
 * Package: com.atguigu.spzx.manager.config
 * Description:
 *
 * @Author 刘强
 * @Create 2024/7/1 10:24
 * @Version 1.0
 */
@Component
public class LoginAuthInterceptor implements HandlerInterceptor {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 登陆认证拦截器：
     *      用户在访问后端接口时都需要进行登录认证，除了登录接口和获取验证码接口
     *      这个拦截器用来进行统一的登陆认证，并且完成了token在后端的延期
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        String requestURI = request.getRequestURI();
//        System.out.println("requestURI = " + requestURI);
        // 0. 判断是否是预检请求，如果是则直接放行
        String method = request.getMethod();
        if("OPTIONS".equals(method)){
            return true;
        }

        // 1. token校验
        String token = request.getHeader("token");
        if(StrUtil.isEmpty(token)){
            responseNoLogin(response);
            return false;
        }
        // 2. 获取用户信息保存到线程本地变量
        String userStr = stringRedisTemplate.opsForValue().get("user:login:" + token);
        if(StrUtil.isEmpty(userStr)){
            // 响应一个Result对象
            responseNoLogin(response);
            return false;
        }
        SysUser sysUser = JSON.parseObject(userStr, SysUser.class);
        AuthContextUtil.set(sysUser);
        // 3. token延期-->更新redis中的当前token过期时间
        stringRedisTemplate.expire("user:login:"+token,2400, TimeUnit.HOURS);
        // 3. 放行
        return true;
    }

    /**
     * 响应用户没有登陆的Result对象
     * @param response
     * @throws IOException
     */
    private static void responseNoLogin(HttpServletResponse response)  {
        // 响应一个Result对象
        response.setContentType("text/html;charset=UTF-8");
        Result result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.print(JSON.toJSONString(result));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if(writer!=null){
                writer.close();
            }
        }
    }

    /**
     * 当前请求处理完毕之后，我们应该删除线程本地变量--->为了避免线程复用时，线程本地变量被复用
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthContextUtil.remove();
    }
}
